<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keywords" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="180">
			</el-table-column>
			<el-table-column prop="name" label="角色名称" width="180" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="标识" width="180"  sortable>
			</el-table-column>
			
			<el-table-column label="操作" width="500">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" size="small" @click="handlePermission(scope.$index, scope.row)">设置权限</el-button>
          <el-button type="success" size="small" @click="handleMenu(scope.$index, scope.row)">设置菜单</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
			</el-pagination>
		</el-col>


		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="saveRoleDate" :close-on-click-modal="false">
			<el-form :model="savaForm" label-width="80px" :rules="savaFormRules" ref="savaForm">
				<el-form-item label="角色名称" prop="name">
					<el-input v-model="savaForm.name" auto-complete="off"></el-input>
				</el-form-item>

        <el-form-item label="角色标识" prop="sn">
          <el-input v-model="savaForm.sn" auto-complete="off"></el-input>
        </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveRoleDate = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

<!--   设置权限弹框-->
    <el-dialog title="设置权限" :visible.sync="setPermissionVisible" :close-on-click-modal="false">
      <el-form :model="rolePermission" label-width="80px" ref="saveForm">
        <!--indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果 -->
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in permissionTree" :key="p.sn">
          <template>
            <!--
            一级权限的复选框
            label:就是当前复选框的值
            -->
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='rolePermission.permissionSns' :label="p.sn"
                         @change='handleCheck(1,indexkey)'>
              {{p.name}}
            </el-checkbox>
            <div style="margin-bottom: 20px;">
              <!--循环一级权限的children 也就是展示二级权限-->
              <div v-for="c in p.children" class="line-check" :key="c.sn"
                   style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                <el-checkbox class="check2" @change='handleCheck(2,indexkey)'
                             v-model="rolePermission.permissionSns" :label="c.sn">
                  {{c.name}}
                </el-checkbox>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setPermissionVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRolePermission" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--   设置菜单弹框-->
    <el-dialog title="设置权限" :visible.sync="setMenuVisible" :close-on-click-modal="false">
      <el-form :model="roleMenu" label-width="80px" ref="saveForm">
        <!--indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果 -->
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllMenu">全选</el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in menusTree" :key="p.id">
          <template>
            <!--
            一级权限的复选框
            label:就是当前复选框的值
            -->
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='roleMenu.menuIds' :label="p.id"
                         @change='handleCheck(1,indexkey)'>
              {{p.name}}
            </el-checkbox>
            <div style="margin-bottom: 20px;">
              <!--循环一级权限的children 也就是展示二级权限-->
              <div v-for="c in p.children" class="line-check" :key="c.id"
                   style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                <el-checkbox class="check2" @change='handleCheck(2,indexkey)'
                             v-model="roleMenu.menuIds" :label="c.id">
                  {{c.name}}
                </el-checkbox>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setMenuVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveMenu" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>


	export default {
		data() {
			return {
				filters: {
					name: ''
				},
				users: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列
        checkAll:false,
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				saveRoleDate: false,//新增界面是否显示
				addLoading: false,
				savaFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入标识', trigger: 'blur' }
          ]
				},
				//新增界面数据
				savaForm: {
					name: '',
          sn:''
				},
        pageInfo:{
				  rows:[],
          total:0
        },
        query:{
				  pageSize:5,
          currentPage:1,
          keywords:''
        },
        setPermissionVisible:false,
        permissionTree:[],
        rolePermission:{
          permissionSns:[],
          roleId:null
        },
        isIndeterminate:false,
        allPermissionSns:[],
        //菜单相关
        menusTree:[],
        setMenuVisible:false,
        roleMenu:{
          menuName:[],
          roleId:null,
          menuIds:[]
        },
        allMenus:[]

			}
		},
		methods: {
		  //handleCheckAllMenu

      //查询所有菜单
      getAllMenuName(){
        this.$http.get("/menu")
                  .then(result=>{
                    result=result.data;
                    if(result.success){
                     let array=result.object;
                      for (let i = 0; i <array.length ; i++) {
                        this.allMenus.push(array[i].id)
                      }

                    }

                  })
                  .catch(result=>{

                  })
      },
      handleCheckAllMenu(val){

        this.roleMenu.menuIds=val?this.allMenus:[]
        //console.log( this.roleMenu.menuIds);

      },

		  //提交菜单
      saveMenu(){

      this.$http.put("/role/menu/add",this.roleMenu)

        .then(result=>{
          console.log(this.roleMenu)
          result=result.data
          if(result.success){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.setMenuVisible=false
            this.getRoles();

          }else {
            this.$message({
              message: result.message,
              type: 'error'
            });

          }


        })
        .catch(result=>{

        })
      },
      //页面刷新
      flushDate(){
        this.getRoles()
      },
		  //设置菜单
      handleMenu(index,row){
        this.roleMenu.roleId=row.id

        this.setMenuVisible=true
        this.getMenuTress();
        this.getMenuDeleted(row.id)
        // // 获取已选中的长度
        // let checkedCount = this.roleMenu.menuIds.length;
        // // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        // this.checkAll = checkedCount === this.allMenus.length;
        // // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        // this.isIndeterminate = checkedCount > 0 && checkedCount < this.allMenus.length;

      },

      //菜单回显
      getMenuDeleted(id){
        this.$http.get("/role/menu/"+id)
                  .then(result=>{
                    result=result.data;
                    console.log(result.object)
                    for (let i = 0; i <result.object.length ; i++) {

                      this.roleMenu.menuIds.push(parseInt(result.object[i]))

                    }
                  })
      },
      //菜单树
      getMenuTress(){
        this.$http.get("/menu/tree")
            .then(result=>{
              result=result.data;
              this.menusTree=result.object;
            })
            .catch(result=>{

            })
      },

      saveRolePermission(){
        this.$http.post("/role/permission",this.rolePermission)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '设置成功!', type: 'success'});
                // 关闭弹框
                this.setPermissionVisible = false;
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })
      },

      // 点击"全选"复选框时,触发的方法
      handleCheckAllChange(val){
        // val:就是当前这个复选框它有没有被选中  true:选中(就是说要将下面的复选框都全部选中)  false:取消选中
        // 如果val=true,就要将所有权限的sn赋值给它们双向绑定的数组,通过双向绑定原则,就可以实现所有的复选框被选中
        this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
        // 取消全选框的那个不确定状态
        this.isIndeterminate = false;
      },
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置

      handleCheck(type, a = 0) {
        // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
        let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
        if (type == 2) { // 二级权限点击
          let index = 0;  //
          this.permissionTree[a].children.map(item => {
            // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
            if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
              index += 1;
            }
          })
          if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
            if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
              this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
            }
          } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
            if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
              this.rolePermission.permissionSns.splice(indexOf, 1);
            }
          }
        } else {  // 一级菜单点击
          if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) < 0) {
                this.rolePermission.permissionSns.push(item.sn)
              }
            })
          } else {
            // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) > -1) {
                this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n == item.sn), 1);
              }
            })
          }
        }
        // 获取已选中的长度
        let checkedCount = this.rolePermission.permissionSns.length;
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allPermissionSns.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
      },
      handlePermission(index,row){
        this.setPermissionVisible=true;
        this.rolePermission.roleId=row.id;
        this.getALLPermission();
        //加载所有唯一标识
        this.getAllPermissionSn()
       this.getSeleted()
      },
      getSeleted(){
        {
          this.$http.get("/role/permission/"+this.rolePermission.roleId)
              .then(result => {
                result = result.data;
                if (result.success) {
                this.rolePermission.permissionSns=result.object
                  // 获取已选中的长度
                  let checkedCount = this.rolePermission.permissionSns.length;
                  // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
                  this.checkAll = checkedCount === this.allPermissionSns.length;
                  // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
                  this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
                }
              })
              .catch(resut => {
              })
        }
      },
      getAllPermissionSn(){
        this.$http.get("/permission/getSn")
            .then(result=>{
              result=result.data;
              if(result.success){
                this.allPermissionSns=result.object
              }
            })
            .catch(resut=>{
            })
      },
      getALLPermission(){
        this.$http.get("/permission")
                  .then(result=>{
                    result=result.data;
                    if(result.success){
                      this.permissionTree=result.object
                    }
                  })
                  .catch(resut=>{
                  })
      },
      search(){
        this.query.currentPage=1;
        this.getRoles();
      },
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getRoles();
			},
			//获取用户列表
			getRoles() {
      this.$http.put("/role",this.query)
        .then(result=>{
          result=result.data;
          if(result.success){
            this.pageInfo=result.object;
          }
        })

			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {

	        this.$http.delete("/role/"+row.id)
                    .then(result =>{

                      result=result.data
                      if(result.success){
                        this.$message({
                          message: '删除成功',
                          type: 'success'
                        });
                      }else {
                        this.$message({
                          message: '删除失败'+result.message,
                          type: 'error'
                        });
                      }
                      // //刷新页面
                      // this.search();
                    })
				}).catch(() => {
          this.$message({
            message: '已取消',
            type: 'info'
          });
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveRoleDate = true;
				this.savaForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
				this.saveRoleDate = true;
				this.savaForm = {
					name: '',
				  sn:''
				};
			},
			//新增
			addSubmit: function () {
				this.$refs.savaForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {

              this.$http.post("/role",this.savaForm)
                  .then(result =>{
                    this.listLoading=false;
                    result=result.data
                    if(result.success){
                      this.$message({
                        message: '保存成功',
                        type: 'success'
                      });
                    }else {
                      this.$message({
                        message: '保存失败'+result.message,
                        type: 'error'
                      });
                    }
                    //刷新页面
                    this.saveRoleDate=false;
                    this.search();
                  })
            });
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

          this.$http.patch("/role",ids)
              .then(result =>{
                this.listLoading=false;

                result=result.data
                if(result.success){
                  this.$message({
                    message: '批量删除成功',
                    type: 'success'
                  });
                }else {
                  this.$message({
                    message: '批量删除失败'+result.message,
                    type: 'error'
                  });
                }
                //刷新页面
                this.search();
              })


				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getRoles();
      this.getAllMenuName()
		}
	}

</script>

<style scoped>

</style>